import { calcDateOffset } from "@/utils/time";

function calcAgeArr(arr: number[]) {
	let res = 0;

	const [year, month] = arr;
	if (year) {
		res += 12 * Number(year);
	}

	if (month) {
		res += Number(month);
	}

	return res;
}

export function parseAge(
	ageStr: Date | number | string | [number, number]
): number {
	if (typeof ageStr === "number") {
		return 12 * ageStr;
	} else if (Array.isArray(ageStr)) {
		return calcAgeArr(ageStr.map((e) => Number(e)));
	} else if (
		typeof ageStr === "string" &&
		ageStr.includes("月") &&
		!(ageStr.includes("岁") || ageStr.includes("年"))
	) {
		const arr = ageStr.match(/\d+(\.\d+)?/g)!;
		return Number(arr[0]);
	} else if (
		typeof ageStr === "string" &&
		(ageStr.includes("岁") || ageStr.includes("年"))
	) {
		const arr = ageStr.match(/\d+(\.\d+)?/g)!;
		return calcAgeArr([Number(arr[0]), Number(arr[1])]);
	} else {
		let time = typeof ageStr === "string" ? new Date(ageStr) : ageStr;

		const age = calcDateOffset(time, new Date());

		return age;
	}
}
